package com.summer.core.action;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.cxl.price.top.service.TopBaseService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.summer.core.bean.Pager;
import com.summer.core.container.SessionContainerUtil;
import com.summer.core.entity.TPK;
import com.summer.core.service.BaseService;
import com.taobao.api.domain.User;

/**
 * 
 * @author Administrator
 * 
 */


public class BaseAction<T extends TPK, S extends BaseService<T, String>> extends
		ActionSupport implements IAction<T, S> {
	
	private static final long serialVersionUID = 6718838811223344556L;
	public static final String VIEW = "view";
	public static final String LIST = "list";
	public static final String STATUS = "status";
	public static final String WARN = "warn";
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	public static final String MESSAGE = "message";
	public static final String CONTENT = "content";
	public User user;
	protected String id;
	protected String[] ids;
	protected Pager pager;
	protected String logInfo;// 日志记录信息
	protected String redirectionUrl;// 操作提示后的跳转URL,为null则返回前一页
	protected List<T> dlist;
	protected T bean = null;
	protected S service = null;
	
	protected String access_token;
	
	public String getAccess_token() {
		return SessionContainerUtil.getSessionContainer(getRequest()).getSessionid();
	}

	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}

	protected TopBaseService topBaseService;

	public String input() {
		return null;
	}

	// 获取Attribute
	public Object getAttribute(String name) {
		return ServletActionContext.getRequest().getAttribute(name);
	}

	// 设置Attribute
	public void setAttribute(String name, Object value) {
		ServletActionContext.getRequest().setAttribute(name, value);
	}

	// 获取Parameter
	public String getParameter(String name) {
		return getRequest().getParameter(name);
	}

	// 获取Parameter数组
	public String[] getParameterValues(String name) {
		return getRequest().getParameterValues(name);
	}

	// 获取Session
	public Object getSession(String name) {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		return session.get(name);
	}

	// 获取Session
	public Map<String, Object> getSession() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		return session;
	}

	// 设置Session
	public void setSession(String name, Object value) {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		session.put(name, value);
	}

	// 获取Request
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	// 获取Response
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	// 获取Application
	public ServletContext getApplication() {
		return ServletActionContext.getServletContext();
	}

	// AJAX输出，返回null
	public String ajax(String content, String type) {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType(type + ";charset=UTF-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(content);
			System.out.println(content);
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// AJAX输出文本，返回null
	public String ajaxText(String text) {
		return ajax(text, "text/plain");
	}

	// AJAX输出HTML，返回null
	public String ajaxHtml(String html) {
		return ajax(html, "text/html");
	}

	// AJAX输出XML，返回null
	public String ajaxXml(String xml) {
		return ajax(xml, "text/xml");
	}

	// 根据字符串输出JSON，返回null
	public String ajaxJson(String jsonString) {
		return ajax(jsonString, "text/html");
	}

	// 根据Map输出JSON，返回null
	public String ajaxJson(Map<String, String> jsonMap) {
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return ajax(jsonObject.toString(), "text/html");
	}

	// 输出JSON警告消息，返回null
	public String ajaxJsonWarnMessage(String message) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, WARN);
		jsonMap.put(MESSAGE, message);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return ajax(jsonObject.toString(), "text/html");
	}

	// 输出JSON成功消息，返回null
	public String ajaxJsonSuccessMessage(String message) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put(MESSAGE, message);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return ajax(jsonObject.toString(), "text/html");
	}

	// 输出JSON错误消息，返回null
	public String ajaxJsonErrorMessage(String message) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, ERROR);
		jsonMap.put(MESSAGE, message);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return ajax(jsonObject.toString(), "text/html");
	}

	// 设置页面不缓存
	public void setResponseNoCache() {
		getResponse().setHeader("progma", "no-cache");
		getResponse().setHeader("Cache-Control", "no-cache");
		getResponse().setHeader("Cache-Control", "no-store");
		getResponse().setDateHeader("Expires", 0);
	}
	
	public String list()throws Exception
	{
		
		//反射bean查询
		
		if(bean!=null)
		{
		Method[] methods=bean.getClass().getMethods();
		Field[] fields=bean.getClass().getFields();
		Map searchMap=pager.getSearchMap();
		
		
		for(Method method:methods)
		{
			String methodName=method.getName();
			if(methodName.startsWith("get"))
			{
				Object value=method.invoke(bean);
				
				String fieldName=methodName.substring(3,4).toLowerCase()+methodName.substring(4);
			
				if(value!=null&&!searchMap.containsKey(fieldName)&&!fieldName.contains("class"))
				{
					searchMap.put(fieldName,method.invoke(bean));
				}
			}
		
			
		}
		}
		pager = service.findByPager(pager);
		return result(LIST);
	}

	public String add() {
		return result(INPUT);
	}
	
	public String edit() {
		
		bean=service.load(id);
		return result(INPUT);
	}

	public String save() {
		if (bean == null) {
			return ERROR;
		}
		service.save(bean);
		redirectionUrl = getRequest().getParameter("redirectionUrl");
		
		return SUCCESS;
	}
	
	public String update() {
		if (bean == null) {
			return ERROR;
		}
		service.update(bean);
		redirectionUrl = getRequest().getParameter("redirectionUrl");
		return SUCCESS;
	}
	
	
	public String delete() {
		service.delete(ids);
		return ajaxJsonSuccessMessage("删除成功！");
	}
	
	

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String[] getIds() {
		return ids;
	}

	public void setIds(String[] ids) {
		this.ids = ids;
	}

	public Pager getPager() {
		return pager;
	}

	public void setPager(Pager pager) {
		this.pager = pager;
	}

	public String getLogInfo() {
		return logInfo;
	}

	public void setLogInfo(String logInfo) {
		this.logInfo = logInfo;
	}

	public String getRedirectionUrl() {
		return redirectionUrl;
	}

	public void setRedirectionUrl(String redirectionUrl) {
		this.redirectionUrl = redirectionUrl;
	}

	public T getBean() {
		return bean;
	}

	public void setBean(T bean) {
		this.bean = bean;
	}

	public S getService() {
		return service;
	}

	public void setService(S service) {
		this.service = service;
	}

	public List<T> getDlist() {
		return dlist;
	}

	public void setDlist(List<T> dlist) {
		this.dlist = dlist;
	}

	/**
	 * 访问路径的前缀
	 * @return
	 */
	public String result(String str)
	{
		String prefix= getLastName(this.getClass().getName()).replace("Action", "").toLowerCase();
		prefix=prefix+"/"+prefix+"_"+str;
		System.out.println(prefix);
		return prefix;
	}
	
	
	
	
	public TopBaseService getTopBaseService() {
		return topBaseService;
	}

	@Resource
	public void setTopBaseService(TopBaseService topBaseService) {
		this.topBaseService = topBaseService;
	}

	public String getLastName(String str)
	{
		String[] array=str.split("\\.");
		int size=array.length;
		String prefix= array[size-1].replace("Action", "");
		return prefix;
	}

}